<?php

namespace Api\Jobs;

use Api\Enums\YidaType;
use Api\Http\Controllers\WechatController;
use Api\Service\YunyangService;
use Carbon\Carbon;
use Clockwork\Request\Log;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Modules\Express\Models\ExpressPlatform;
use Modules\Member\Models\Members;
use Modules\Member\Models\MembersPriceLog;
use Modules\Member\Models\MembersProfit;
use Modules\Order\Models\Orders;
use Illuminate\Support\Facades\Log as Logs;

class YidaPushTask implements ShouldQueue
{
    use Queueable, Dispatchable, InteractsWithQueue, SerializesModels;

    private mixed $push;


    /**
     * Create a new job instance.
     */
    public function __construct($push)
    {
        $this->push = $push;

    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $push = (array)$this->push;
        $pushType = $push['pushType'];
        if(!isset($push['thirdNo'])){
            return;
        }
        $orderSn = $push['thirdNo']; //运单号
        $orderInfo = Orders::where('order_sn', $orderSn)->first();

        $obj = $push['contextObj'];
        $content = current(array($obj));
        if (empty($orderInfo)) {
            return;
        }
        $userInfo = Members::find($orderInfo->user_id);
        $config = ExpressPlatform::where('express_code', $orderInfo->platform_id)->where('type', $orderInfo->channel_tag)->first();
        $wechat = new WechatController();
        if ($pushType == 1) {
            //更改快递状态
            $status = $content['ydOrderStatus'];
            $type = match ($status) {
                '1', '11' => YidaType::LANSHOU->name(),
                '2' => YidaType::YUNSHU->name(),
                '3' => YidaType::QIANSHOU->name(),
                '6' => YidaType::REJECT->name(),
                default =>YidaType::CANCEL->name(),

            };

            $typeCode = match ($status) {
                '1', '11' => YidaType::LANSHOU->value(),
                '2' => YidaType::YUNSHU->value(),
                '3' => YidaType::QIANSHOU->value(),
                '6' => YidaType::REJECT->value(),
                default => YidaType::CANCEL->value(),

            };

            $orderInfo->type = $type;
            $orderInfo->type_code = $typeCode;
            if($typeCode == 3){
                //完成订单处理
                $orderInfo->status = 2;
                $profitList = MembersProfit::where('order_id', $orderInfo->id)->get();
                foreach ($profitList as $v) {
                    if ($v->status == 2) {
                        continue;
                    }
                    $v->status = 1;
                    $money = $v->profit;
                    if (Members::where('id', $v->user_id)->increment('price', $money)) {
                        $v->save();
                        //增加资金明细
                        //增加余额变动日志
                        $priceLog = [];
                        $priceLog = new MembersPriceLog();
                        $priceLog->user_id = $v->user_id;
                        $priceLog->start_user_id = $orderInfo->user_id;
                        $priceLog->money = $v->profit;
                        $priceLog->type = 2;
                        $priceLog->status = 1;
                        $priceLog->order_sn = $orderInfo->order_sn;
                        $priceLog->waybill = $orderInfo->waybill;
                        $priceLog->save();
                    }
                }
            }

            if($typeCode == 99 && !empty($orderInfo->paid_at)){
                $orderInfo->is_overweight = 0;
                $orderInfo->is_haocai = 0;
                $orderInfo->type = '已退款';
                $orderInfo->type_code = 5;
                $orderInfo->status = 2;
                $wechat->refundOrder($orderInfo->order_sn, $orderInfo->money);
            }
            if($typeCode == 99 && empty($orderInfo->paid_at)){
                $orderInfo->type = '已取消';
                $orderInfo->type_code = 99;
                $orderInfo->is_overweight = 0;
                $orderInfo->is_haocai = 0;
                $orderInfo->status = 2;
            }

            $orderInfo->save();
        } elseif ($pushType == 2) {
            //计费变更
            $realWeight = $content['realWeight'];
            $calcWeight = $content['calcFeeWeight'] ?? 0;
            $weight = ceil(max($realWeight, $calcWeight));

            //获取首重续重价格
            if(isset($content['priceRule'])){
                foreach ($content['priceRule'] as $newRule) {
                    $start = $newRule['start'];
                    $end = $newRule['end'];
                    if($weight > $start && $weight <= $end){
                        $priceOne = bcadd((string)$newRule['first'], $config['price_one']);
                        $priceMore = bcadd((string)$newRule['add'], $config['price_more']);
                    }
                }
            }else{
                $priceOne = $orderInfo->price_one;
                $priceMore = $orderInfo->price_more;
            }
            $freightBase = $content['freightBase'];
            $blockList = $content['feeBlockList'];
            if($freightBase == 'weight'){
                //耗材费
                if(!empty($blockList) && is_array($blockList)){
                    foreach ($blockList as $v){
                        //有耗材费
                        if($v['type'] == 3 && $orderInfo->haocai_money == 0){
                            $orderInfo->haocai_sn = uniqid();
                            $orderInfo->haocai_money = $v['fee'];
                            $orderInfo->is_haocai = 1;
                            $orderInfo->haocai_at = time();
                        }
                    }
                }


                //如果实际重量大于填写重量
                if($weight > $orderInfo->weight){

                    $overWeight = ceil(bcsub($weight, $orderInfo->weight, 2));
                    //续重分销
                    $overWeightMoney = bcmul($priceMore, $overWeight, 2);
                    $orderInfo->is_overweight = 1;
                    $orderInfo->cal_weight = $weight;
                    $orderInfo->overweight_sn = uniqid();
                    $orderInfo->overweight_money = $overWeightMoney;
                    $orderInfo->overweight_at = time();
                    //续重分销无效重新计算
//                    MembersProfit::where('order_id',$orderInfo->id)->where('type',4)->update(['status'=>2]);
//                    //首重续重分销计算
//                    $push['orderId'] = $orderInfo->id;
//                    $push['userId'] = $orderInfo->user_id;
//                    $push['useCoupon'] = !empty($orderInfo->coupon_id);
//                    $push['first'] = false;
//                    $push['more'] = true;
//                    $push['calWeight'] = $overWeight;
//                    $push['platform'] = $orderInfo->platform_id;
//                    MemberProfitTask::dispatch($push);

                    //小程序提醒超重
                    $message = [];
                    $message['thing1'] = ['value' => $orderInfo->tag_type];
                    $message['character_string2'] = ['value' => $orderInfo->waybill];
                    $message['number4'] = ['value' => $overWeight];
                    $message['amount5'] = ['value' => $overWeightMoney];
                    $message['thing6'] = ['value' => '请及时支付超重费用,以免影响寄件'];
                    $obj = (object)$message;

                    $page = 'pages/user/addMoney';
                    $wechat->sendMessage('rYgOcm2rCdA2ZVX-bufrhRkM2QYHxZ7NRURrqt2Pyjw', $userInfo->open_id, $obj, $page);
                }elseif($weight < $orderInfo->weight){
                    //重量小于实际重量退款
                    $refundWeight = bcsub($orderInfo->weight,$weight);
                    $refundMoney = bcmul($priceMore, $refundWeight, 2);
                    $wechat->refundOrder($orderInfo->order_sn, $refundMoney);
                    $orderInfo->is_overweight = 0;
                    $orderInfo->overweight_money = 0;
                    $orderInfo->cal_weight = $weight;
                    $push['orderId'] = $orderInfo->id;
                    $push['userId'] = $orderInfo->user_id;
                    $push['useCoupon'] = !empty($orderInfo->coupon_id);
                    $push['first'] = false;
                    $push['more'] = true;
                    $push['calWeight'] = $refundWeight;
                    $push['platform'] = $orderInfo->platform_id;
                    MemberProfitTask::dispatch($push);
                }


            }elseif ($freightBase == 'fee'){
                $realMoney = 0;
                $realMoney += $content['feeBlockList'][0]['fee'];
                $realMoney =  bcmul($realMoney,'1.1',2);
                $orderInfo->fee_type = 'fee';
                $orderInfo->overweight_money = bcsub($realMoney,$orderInfo->money,2);
                $orderInfo->is_overweight = 1;
            }
            $orderInfo->save();
        } elseif ($pushType == 3) {

            //获取快递员信息
            $orderInfo->postman_name = $content['courierName'];
            $orderInfo->postman_mobile = $content['courierPhone'];
            $orderInfo->save();
        } elseif ($pushType == '5') {
            //换单

        }
    }
}
